import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'dart:convert' as convert;
import 'package:http/http.dart' as http;
import 'package:bklx/Arg.dart' as arg;
import 'dart:math';
import 'OneBuildPage.dart';
import 'Search.dart';

class AllBuildPage extends StatefulWidget{
  AllBuildPage({Key key}):super(key:key);
  _AllBuildPageState createState() => _AllBuildPageState();
}

class _AllBuildPageState extends State<AllBuildPage> with AutomaticKeepAliveClientMixin{
  @override
  bool get wantKeepAlive => true;

  var NetPicUrl;
  var contain = List();
  EasyRefreshController _controller;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = EasyRefreshController();
    this.NetPicUrl = arg.pic_url[Random().nextInt(arg.pic_url.length)];
    getData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    // TODO: implement build
    return Scaffold(
      body:
        EasyRefresh(
          firstRefresh: true,
          controller: _controller,
          enableControlFinishRefresh: true,
          enableControlFinishLoad: true,
          child:
            CustomScrollView(
              slivers: <Widget>[
                SliverAppBar(
                  pinned: true,
                  elevation: 0,
                  expandedHeight: 250,
                  flexibleSpace: FlexibleSpaceBar(
                    title: Text('全部教学楼'),
                    background: Image.asset(
                      this.NetPicUrl,
                      fit: BoxFit.cover,
                    ),
                  ),
                  actions: <Widget>[
                    IconButton(
                      icon: Icon(Icons.search),
                      onPressed: (){
                        showSearch(context: context, delegate: searchBarDelegate());
                      },
                    )
                  ],
                ),
                SliverFixedExtentList(
                  delegate: SliverChildBuilderDelegate(
                      (context,index){
                        return CreateCard(
                            this.contain[index]['BuildName'],
                            this.contain[index]['MaxNum'],
                            this.contain[index]['Num'],
                            this.contain[index]['Percentage']);
                      },
                      childCount: this.contain.length,
                  ),
                  itemExtent: 200,
                )
              ],
            ),
//          onLoad: () async{
//            await Future.delayed(Duration(seconds: 1),() {
//              setState(() {
//                this.contain.add(this.contain.length + 1);
//              });
//              _controller.finishLoad();
//            });
//          },

          onRefresh: () async{
            await Future.delayed(Duration(seconds: 1), () {
              setState(() {
                this.NetPicUrl = arg.pic_url[Random().nextInt(arg.pic_url.length)];
                getData();
              });
              _controller.finishRefresh(success: true);
            });
          },
        ),
    );
  }

  Widget CreateCard(String BuildName,int MaxNum,int Num,var Percentage){
    return Card(
      elevation: 15.0,
      shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(14.0))),
      child: Column(
        children: [
          ListTile(
            title: Text('${BuildName}'),
            leading: Icon(
              Icons.school,
              color: Colors.blue,
            ),
            trailing: Icon(
              Icons.arrow_forward_ios,
            ),
            onTap: (){
              Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => OneBuildPage(BuildName))
              );
            },
            ),
          Divider(),
          ListTile(
            title: Text('当前人数:${Num}  最大人数:${MaxNum}'),
            leading: Icon(
              Icons.people,
              color: Colors.blue,
            ),
          ),
          ListTile(
            title: Text('百分比:${Percentage * 100}%'),
            leading: Icon(
              Icons.more_vert,
            ),
          )
        ],
      ),
    );
  }

  getData() async{
    var url = 'https://www.fjnu-study.cn/request/inf_request.php?type=AllBuild';
    var response = await http.get(url);
    if(response.statusCode == 200){
      var jsonRes = convert.jsonDecode(response.body);
      setState(() {
        this.contain = jsonRes;
        NameTransform();
      });
    }
    else{
      print('请求错误，错误代码：${response.statusCode}');
    }
  }

  void NameTransform(){
    if(this.contain.length > 0){
      for(var i = 0;i < this.contain.length;i++){
        switch(this.contain[i]['BuildName']){
          case 'ZM':{
            this.contain[i]['BuildName'] = '知明';
          }break;
          case 'XD':{
            this.contain[i]['BuildName'] = '笃行';
          }break;
          case 'LC':{
            this.contain[i]['BuildName'] = '立诚';
          }break;
          case 'ZG':{
            this.contain[i]['BuildName'] = '致广';
          }break;
        }
      }
    }
  }
}